<template>
  <div class="fillcontain">
    <div class="contain">
      <!-- 列表 -->
      <el-table :data="tableDatas">
        <el-table-column
          v-for="(col, i) in conditionList"
          :property="col.divisorIdentify"
          :key="i"
          :index="i"
          :label="col.conditionDesc"
        >
          <template slot="header" slot-scope="scope">
            <el-tooltip
              v-if="
                conditionList[scope.column.index] &&
                conditionList[scope.column.index].headType == '0' &&
                conditionList[scope.column.index].decisionCode == 'RCODE'
              "
              class="item"
              effect="dark"
              :content="scope.column.label"
              placement="top"
            >
              <span>{{ scope.column.label }}</span>
            </el-tooltip>
            <el-tooltip
              v-if="
                conditionList[scope.column.index] &&
                conditionList[scope.column.index].headType == '0' &&
                conditionList[scope.column.index].decisionCode == 'RNAME'
              "
              class="item"
              effect="dark"
              content="规则组名称"
              placement="top"
            >
              <span>规则组名称</span>
            </el-tooltip>
            <el-tooltip
              v-if="
                conditionList[scope.column.index] &&
                conditionList[scope.column.index].headType == '1'
              "
              class="item"
              effect="dark"
              :content="scope.column.label + '(条件)'"
              placement="top"
            >
              <span>
                <i
                  v-if="showDel"
                  class="el-icon-circle-close"
                  @click="delcol(scope, scope.column)"
                ></i>
                {{ scope.column.label }} (条件)
              </span>
            </el-tooltip>
            <el-tooltip
              v-if="
                conditionList[scope.column.index] &&
                conditionList[scope.column.index].headType == '2'
              "
              class="item"
              effect="dark"
              :content="scope.column.label + '(动作)'"
              placement="top"
            >
              <span>
                <i
                  v-if="showDel"
                  class="el-icon-circle-close"
                  @click="delcol(scope, scope.column)"
                ></i>
                {{ scope.column.label }} (动作)
              </span>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <div v-if="scope.row[scope.column.property]">
              <el-tooltip
                class="item"
                effect="dark"
                placement="top"
                :content="scope.row[scope.column.property].conditionDesc"
              >
                <el-input
                  v-model="scope.row[scope.column.property].conditionDesc"
                  readonly
                  disabled
                ></el-input>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="!isShow"
          header-align="center"
          width="200"
          align="center"
          label="操作"
        >
          <template slot-scope="scope">
            <el-button
              v-if="!isconflict"
              type="text"
              size="small"
              @click="addDecisionRow(scope.row, scope.$index)"
              >复制</el-button
            >
            <el-button
              v-if="scope.row['RCODE'] && scope.row['RCODE'].isEffect"
              @click.native="editRow(scope.row, scope.$index)"
              :disabled="scope.row['RCODE'].isEffect == '0' ? true : false"
              type="text"
              size="small"
              >修改</el-button
            >

            <el-button type="text" size="small" @click="delDecision(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 弹窗, 填值 -->
    <el-dialog
      title="详情"
      :close-on-click-modal="false"
      width="60%"
      :visible.sync="addvisible"
      append-to-body
    >
      <el-form
        ref="dataForm"
        @keyup.enter.native="adddataFormSubmit()"
        label-width="80px"
      >
        <el-col :span="12" v-for="(item, index) in adddataForm" :key="index">
          <rules-input v-if="item && item.headType == '0'">
            <template slot="ruleinput">
              <el-input
                v-if="item && item.decisionCode == 'RCODE'"
                v-model="item.conditionDesc"
                disabled
                placeholder="请输入内容"
              ></el-input>
              <el-input
                v-else
                v-model="item.conditionDesc"
                placeholder="请输入内容"
              ></el-input>
            </template>
            <template v-if="item && item.headType == '0'" slot="inputdes">{{
              item["conditionDesc1"]
            }}</template>
          </rules-input>
          <!-- 非方法 固定值 -->
          <rules-input v-if="item && item.headType == '1'">
            <template v-if="item && item.iszhixing" slot="ruleinput">
              <el-select
                v-model="item.isExcute"
                filterable
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="i in excuteTypes"
                  :key="i.value"
                  :label="i.label"
                  :value="i.value"
                  @click.native="changeExeType(item, index)"
                ></el-option>
              </el-select>
            </template>
            <template
              v-if="item && item.conditionType == '4' && item.divisor"
              slot="ruleinput"
            >
              <!-- 规则因子 非方法 且文本类型 则是输入框-->
              <el-input
                v-if="
                  item.divisor.valueType === '2' &&
                  item.divisor.divisorType === '0' &&
                  item.divisor.itemValueType === '1'
                "
                v-model="item.rightValue"
                @blur="insertV('41', item)"
                placeholder="文本值"
              ></el-input>
              <!-- 规则因子 非方法 且枚举类型 则是下拉框-->
              <el-select
                v-if="
                  item.divisor.divisorType === '0' &&
                  item.divisor.valueType === '2' &&
                  item.divisor.itemValueType === '2'
                "
                v-model="item.rightValue"
                filterable
                clearable
                placeholder="请选择条件"
              >
                <el-option
                  v-for="i in enumList[`${item.divisor.id}list`]"
                  :key="i.enumCode"
                  :label="i.label"
                  :value="i.enumCode"
                  @click.native="insertV('42', item, i)"
                ></el-option>
              </el-select>
              <!-- 规则因子 非方法 且模型类型 则是模型-->
              <el-select
                v-if="
                  item.divisor.divisorType === '0' &&
                  item.divisor.valueType === '2' &&
                  item.divisor.itemValueType === '3'
                "
                v-model="item.rightEntityId"
                filterable
                clearable
                placeholder="请选择模型"
              >
                <el-option
                  v-for="i in checkEntity"
                  :key="i.entityId"
                  :label="i.entityName"
                  :value="i.entityId"
                  @click.native="insertV('43', item, i)"
                ></el-option>
              </el-select>
              <!--  -->
              <el-select
                v-if="
                  item.divisor.divisorType === '0' &&
                  item.divisor.valueType === '2' &&
                  item.divisor.itemValueType === '3'
                "
                v-model="item.rightProperty"
                filterable
                clearable
                placeholder="请选择属性"
              >
                <el-option
                  v-for="i in childList[`${item.rightEntityId}list`]"
                  :key="i.itemId"
                  :label="i.label"
                  :value="i.itemId"
                  @click.native="insertV('44', item, i)"
                ></el-option>
              </el-select>
              <el-col
                :span="24"
                v-if="
                  item.divisor.divisorType === '1' && item.divisorMethodParams
                "
              >
                <el-col
                  :span="12"
                  v-for="(p, index) in item.divisorMethodParams"
                  :key="index"
                >
                  <el-col :span="12">
                    <el-input
                      v-model="p.name"
                      @blur="insertV('45', item, p)"
                      :placeholder="p.desc"
                    ></el-input>
                  </el-col>
                </el-col>
              </el-col>
            </template>
            <template v-if="item && item.headType == '1'" slot="inputdes">{{
              item["conditionDesc1"] + "(条件)"
            }}</template>
          </rules-input>
          <rules-input v-if="item && item.headType == '2'">
            <template v-if="item && item.iszhixing" slot="ruleinput">
              <el-select
                v-model="item.isExcute"
                filterable
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="i in excuteTypes"
                  :key="i.value"
                  :label="i.label"
                  :value="i.value"
                  @click.native="changeExeType(item, index)"
                ></el-option>
              </el-select>
            </template>
            <!-- 规则因子 -->
            <template
              v-if="item && item.conditionType == '4' && item.divisor"
              slot="ruleinput"
            >
              <el-input
                v-if="
                  item.divisor.valueType === '2' &&
                  item.divisor.divisorType === '0' &&
                  item.divisor.itemValueType === '1'
                "
                v-model="item.rightValue"
                @blur="insertV('41', item)"
                placeholder="文本值"
              ></el-input>
              <!-- 规则因子 非方法 且枚举类型 则是下拉框-->
              <el-select
                v-if="
                  item.divisor.divisorType === '0' &&
                  item.divisor.valueType === '2' &&
                  item.divisor.itemValueType === '2'
                "
                v-model="item.rightValue"
                filterable
                clearable
                placeholder="请选择条件"
              >
                <el-option
                  v-for="i in actionEnumList[`${item.divisor.id}list`]"
                  :key="i.enumCode"
                  :label="i.label"
                  :value="i.enumCode"
                  @click.native="insertV('42', item, i)"
                ></el-option>
              </el-select>
              <!-- 规则因子 非方法 且模型类型 则是模型-->
              <el-select
                v-if="
                  item.divisor.divisorType === '0' &&
                  item.divisor.valueType === '2' &&
                  item.divisor.itemValueType === '3'
                "
                v-model="item.rightEntityId"
                filterable
                clearable
                placeholder="请选择模型"
              >
                <el-option
                  v-for="i in checkEntity"
                  :key="i.entityId"
                  :label="i.entityName"
                  :value="i.entityId"
                  @click.native="insertV('43', item, i)"
                ></el-option>
              </el-select>
              <!--  -->
              <el-select
                v-if="
                  item.divisor.divisorType === '0' &&
                  item.divisor.valueType === '2' &&
                  item.divisor.itemValueType === '3'
                "
                v-model="item.rightProperty"
                filterable
                clearable
                placeholder="请选择属性"
              >
                <el-option
                  v-for="i in childList[`${item.rightEntityId}list`]"
                  :key="i.itemId"
                  :label="i.label"
                  :value="i.itemId"
                  @click.native="insertV('44', item, i)"
                ></el-option>
              </el-select>
              <!-- 规则因子 方法-->
              <el-col
                :span="24"
                v-if="
                  item.divisor.divisorType === '1' && item.divisorMethodParams
                "
              >
                <el-col
                  :span="12"
                  v-for="(p, index) in item.divisorMethodParams"
                  :key="index"
                >
                  <el-col :span="12">
                    <el-input v-model="p.name" :placeholder="p.desc"></el-input>
                  </el-col>
                </el-col>
              </el-col>
            </template>
            <template v-if="item && item.headType == '2'" slot="inputdes">{{
              item["conditionDesc1"] + "(动作)"
            }}</template>
          </rules-input>
        </el-col>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button
          :plain="true" type="info"
          @click="adddataFormSubmit('dynamicValidateForm')"
          >确定</el-button
        >
        <el-button @click="addvisible = false">返回</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { entityList, entityItemList } from "@/api/baseConfig/entity";
import { getData } from "@/api/baseConfig/conditionDivisor";
import {
  getActionData,
  listActionDivisorData,
} from "@/api/baseConfig/actionDivisor";
import { saveDecisions, getDecisionsByGroup } from "@/api/ruleConfig/decision";
import { changeClashInfo } from "@/api/task";
import constant from "@/api/constant";
import { listConditionDivisorData } from "@/api/baseConfig/conditionDivisor";

export default {
  data() {
    return {
      recodes: {
        isEntityEdit: false, //是否修改实体
        delHead: false, //是否删除列
        addHead: false, //是否新增列
        delRows: [], //是否删除行
        editRows: [], //是否修改行
        addRows: [], //是否新增行
      },
      conditionDivisorList: [],
      actionDivisorList: [],
      childList: {},
      enumList: {}, //条件枚举列表
      actionEnumList: {}, //动作枚举列表
      ruleList: [], //表头规则名称，编码
      tempHeaderList: [], //表头规则名称，编码
      isIndex: null,
      sysbols: constant.ruleConfig.sysbols,
      actionSysbols: constant.ruleConfig.actionSysbols,
      rightEntityItemInfos: [],
      excuteTypes: constant.ruleConfig.excuteTypes,
      adddataForm: [],
      addvisible: false,
      addactionVisible: false,
      showDel: false,
      fileList: [],
      rowIndex: null, //行索引
      colIndex: null, //列索引
      condition: [], //当前表头信息
      delList: [], //当前表头信息
      delHeadList: [], //当前表头信息
      editConditionVisible: false,
      entityList: [],
      //   conditionList: [], //表头信息
      chooseIndex: 0,
      addConditionVisible: false,
      //   tableDatas: [], //决策表数据
      groupTypes: constant.ruleConfig.groupTypes,
      addOrUpdateVisible: false,
      // checkEntity: [],
      dataList: [],
      isDisabled: false,
      visible: false,
      entitysProperties: [],
      dataRule: {},
    };
  },
  created() {
    let id = this.$route.params.id;
    this.init(id);
  },
  watch: {
    adddataForm: {
      handler: function (newVal, oldVal) {
        this.adddataForm = newVal;
      },
      deep: true,
    },
  },
  props: {
    versionType: {
      type: String,
    },
    dataForm: {
      type: Object,
    },
    isShow: {
      type: Boolean,
    },
    checkEntity: {
      type: Array,
    },
    isconflict: {
      type: Boolean,
    },
    tableDatas: {
      type: Array,
    },
    conditionList: {
      type: Array,
    },
  },
  components: {},

  mounted() {
    //   // console.log(this.dataForm,'dataForm');
  },
  methods: {
    delDecision(data) {
      // console.log(data);
      this.$confirm(`确定进行[删除]操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.tableDatas.splice(data.$index, 1);
          this.$emit("delDecision", data.row);
        })
        .catch(() => {});
    },
    // 记录输入的值
    insertV(type, data, val) {
      // debugger
      //规则因子 输入值
      if (type === "41") {
        data.descData[0] = { k: data.rightValue, v: data.rightValue };
      }
      if (type === "45") {
        // 规则因子 输入值
        data.descData[0] = { k: val.name, v: val.name };
      }
      //枚举
      if (type === "42") {
        data.descData[0] = { k: data.enumValue, v: data.enumCode };
        // console.log(this.adddataForm);
      }
      //模型
      if (type === "43") {
        data.descData[0] = {
          k: val.entityName + " 的",
          v: "$" + val.entityIdentify + ".",
        };
        this.changeRightEntity(val);
      }
      //属性
      if (type === "44") {
        let s =
          val.itemIdentify.substring(0, 1).toLocaleUpperCase() +
          val.itemIdentify.substring(1, val.itemIdentify.length);
        let v = "get" + s + "()";
        data.descData[1] = { k: val.itemName, v: v };
      }
      // console.log(type, data, val);
    },
    //选择实体类
    changeRightEntity(item) {
      let params = {
        id: item.entityId + "",
      };
      let name = item.entityId + "list";
      this.childList[name] = [];
      entityItemList(params).then((res) => {
        if (res.data.data) {
          res.data.data.forEach((item) => {
            item["label"] = item.itemName + "--" + item.itemIdentify;
            this.childList[name].push(item);
          });
          // console.log(this.childList);
          this.$forceUpdate();
        }
      });
    },
    // 是否执行
    changeeExeType(item, index) {
      if (item.isExcute === "N") {
      } else {
        this.$set(this.adddataForm[index], "showMthod", true);
        this.$set(this.adddataForm[index], "showTxt", true);
        this.$set(this.adddataForm[index], "showSysbol", true);
      }
      this.$set(this.adddataForm[index], "isExcute", item.isExcute);
      // console.log(this.adddataForm);
    },

    //获取实体属性
    getItems(rightEntityId) {
      let params = {
        id: rightEntityId + "",
      };
      let name = rightEntityId + "list";
      let arr = [];
      entityItemList(params).then((res) => {
        if (res.data.data) {
          res.data.data.forEach((item) => {
            item["label"] = item.itemName + "--" + item.itemIdentify;
            // this.rightEntityItemInfos.push(item);
            arr.push(item);
          });
          this.childList[name] = arr;
          // console.log(this.childList);
        }
      });
    },
    initDivisor() {
      let params = {
        is_effect: "1",
      };
      listConditionDivisorData(params).then((res) => {
        this.conditionDivisorList = res.data.data;
      });
      listActionDivisorData(params).then((res) => {
        this.actionDivisorList = res.data.data;
      });
    },
    //初始化行数据 dataForm 数据 ，item 头部信息,headType条件、动作
    setInitData(dataForm, item, ele) {
      //如果是因子
      if (dataForm && dataForm.conditionType === "4") {
        let parms = { id: dataForm.divisorId };
        if (dataForm.headType && dataForm.headType === "1") {
          // console.log(this.conditionDivisorList);
          this.conditionDivisorList.forEach((item) => {
            // console.log(item.id,dataForm.divisorId);
            if (item.id === dataForm.divisorId) {
              dataForm.divisor = item;
              if (dataForm.divisor.methodParams) {
                // console.log(dataForm.divisor.methodParams,'222');
                // console.log(this.adddataForm);
                // dataForm.showMthod = true;
                if (dataForm.methodParams) {
                  // dataForm.divisorMethodParams = JSON.parse(
                  //   dataForm.methodParams
                  // );
                  dataForm.divisorMethodParams = [];
                  let m = JSON.parse(dataForm.methodParams);
                  let arr = JSON.parse(dataForm.divisor.methodParams);
                  for (var i = 0; i < m.length; i++) {
                    let mp = m[i];
                    mp["attri"] = arr[i].name;
                    dataForm.divisorMethodParams.push(mp);
                  }
                } else {
                  // dataForm.divisorMethodParams = JSON.parse(
                  //   dataForm.divisor.methodParams
                  // );
                  dataForm.divisorMethodParams = [];
                  let arr = JSON.parse(dataForm.divisor.methodParams);
                  arr.forEach((item) => {
                    item["attri"] = item.name;
                    dataForm.divisorMethodParams.push(item);
                  });
                }
              } else {
                dataForm.divisorMethodParams = "";
              }
              if (dataForm.divisor.divisorType === "1") {
                dataForm.showMthod = true;
              } else if (dataForm.divisor.divisorType === "0") {
                // 输入值
                if (dataForm.divisor.valueType === "2") {
                  dataForm.showTxt = true;
                }
                //模型
                if (dataForm.divisor.itemValueType === "3") {
                  if (dataForm.rightEntityId) {
                    this.getItems(dataForm.rightEntityId);
                  }
                }
              }
            }
          });
          if (dataForm.divisor && dataForm.divisor.itemValueType === "2") {
            let name = dataForm.divisor.id + "list";
            let arr = [];
            getData(parms).then((res) => {
              res.data.data.enumList.forEach((item) => {
                item["label"] = item.enumCode + "--" + item.enumValue;
                arr.push(item);
              });
              this.enumList[name] = arr;
              // console.log(this.enumList);
              this.$forceUpdate();
            });
          }
        }
        if (dataForm.headType && dataForm.headType === "2") {
          this.actionDivisorList.forEach((item) => {
            // debugger
            if (item.id === dataForm.divisorId) {
              dataForm.divisor = item;
              if (dataForm.divisor && dataForm.divisor.methodParams) {
                // dataForm.showMthod = true;
                // dataForm.divisorMethodParams = JSON.parse(
                //   dataForm.divisor.methodParams
                // );
                dataForm.divisorMethodParams = [];
                let arr = JSON.parse(dataForm.divisor.methodParams);
                arr.forEach((item) => {
                  item["attri"] = item.name;
                  dataForm.divisorMethodParams.push(item);
                });
              }
              if (dataForm.divisor && dataForm.divisor.divisorType === "1") {
                // dataForm.showMthod = true;
                if (dataForm.conditionDesc) {
                  let param = [];
                  param = dataForm.conditionDesc.split(",");
                  if (dataForm.divisor.methodParams) {
                    dataForm.divisorMethodParams = JSON.parse(
                      dataForm.divisor.methodParams
                    );
                    param.forEach((e, i) => {
                      // debugger
                      dataForm.divisorMethodParams[i]["attri"] =
                        dataForm.divisorMethodParams[i].name;
                      dataForm.divisorMethodParams[i].name = e;
                    });
                  }
                }
              } else if (dataForm.divisor.divisorType === "0") {
                // 输入值
                if (dataForm.divisor.valueType === "2") {
                  // dataForm.showTxt = true;
                }
                //模型
                if (dataForm.divisor.itemValueType === "3") {
                  if (dataForm.rightEntityId) {
                    this.getItems(dataForm.rightEntityId);
                  }
                }
              }
            }
          });
          if (
            dataForm &&
            dataForm.divisor &&
            dataForm.divisor.itemValueType === "2"
          ) {
            let name = dataForm.divisor.id + "list";
            let arr = [];
            getActionData(parms).then((res) => {
              res.data.data.enumList.forEach((item) => {
                item["label"] = item.enumCode + "--" + item.enumValue;
                arr.push(item);
              });
              this.actionEnumList[name] = arr;
              // console.log(this.actionEnumList);
              this.$forceUpdate();
            });
          }
        }
      } else {
      }

      // if (dataForm.isExcute === "N") {
      //     dataForm.showTxt = false;
      //     dataForm.showSysbol = false;
      //     // dataForm.showMthod = false;
      // }

      return dataForm;
    },
    // 新增/修改行
    editRow(ele, index) {
      // console.log(ele, index);
      this.$emit("changeeditRow", ele);
    },
    isadddataForm() {
      // 是否显示执行
      this.adddataForm.forEach((e) => {
        if (e) {
          if (!e.divisor) {
            e.iszhixing = false;
          } else {
            // 非方法，固定值
            if (e.divisor && e.divisor.divisorType == "0") {
              if (!e.divisor.valueType || e.divisor.valueType == "1") {
                e.iszhixing = true;
              } else {
                e.iszhixing = false;
              }
            } else if (e.divisor && e.divisor.divisorType == "1") {
              // console.log(e, "1234");
              // 方法
              if (e.divisor.methodParams) {
                let param = JSON.parse(e.divisor.methodParams);
                if (param.length) {
                  e.iszhixing = false;
                } else {
                  e.iszhixing = true;
                }
              } else {
                e.iszhixing = true;
              }
            }
          }
        }
      });
      // console.log(this.adddataForm);
    },
    //0禁用、1启用
    editIsEffect(value, type) {
      // console.log(value);
      // console.log(this.conditionList);
      let msg = "";
      if (type === 0) {
        msg = "禁用";
      } else {
        msg = "启用";
      }
      this.$confirm("确定要" + msg + "此列吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.conditionList.forEach((ele) => {
            if (value.row[ele.decisionCode].isEffect == "1") {
              value.row[ele.decisionCode].isEffect = "0";

              if (ele.decisionCode === "RCODE") {
                value.row[ele.decisionCode].editType = constant.DEL; //删除
              }
            } else if (value.row[ele.decisionCode].isEffect == "0") {
              value.row[ele.decisionCode].isEffect = "1";

              if (ele.decisionCode === "RCODE") {
                value.row[ele.decisionCode].editType = constant.EDIT; //修改
              }
            }
          });
        })
        .catch(() => {});
    },

    //校验数据
    validForm() {
      for (let i = 0; i < this.adddataForm.length; i++) {
        let dataForm = this.adddataForm[i];
        if (dataForm.isExcute === "Y" && dataForm.headType != "0") {
          if (dataForm.conditionType === "4") {
            if (
              dataForm.divisor.divisorType === "0" &&
              dataForm.divisor.valueType === "2"
            ) {
              if (
                dataForm.divisor.itemValueType != "3" &&
                !dataForm.rightValue
              ) {
                // this.$message.error("请将因子补充完整");
                // return false;
                dataForm.isExcute = "N";
              }
              if (dataForm.divisor.itemValueType === "3") {
                //模型属性
                if (!dataForm.rightEntityId || !dataForm.rightProperty) {
                  dataForm.isExcute = "N";
                  // this.$message.error("请将模型及属性补充完整");
                  // return false;
                }
              }
            } else {
              if (dataForm.divisorMethodParams) {
                let num = 0;
                for (var j = 0; j < dataForm.divisorMethodParams.length; j++) {
                  let item = dataForm.divisorMethodParams[j];
                  let value = item.name;
                  if (!value) {
                    // this.$message.error("请输入" + item.desc);
                    // return false;
                    num++;
                  }
                  if (item.type === "int") {
                    const digit = /^[0-9]*$/;
                    if (!digit.test(value)) {
                      // this.$message.error(item.desc + "只能输入数字");
                      // return false;
                    }
                  }
                }
                //如果参数都没填 默认不执行
                if (num == dataForm.divisorMethodParams.length) {
                  dataForm.isExcute = "N";
                }
              }
            }
          }
        }
      }
      return true;
    },
    //设置表格显示的数据
    showValue(dataForm) {
      // dataForm.conditionExpression = ''
      dataForm.conditionDesc = "";
      if (dataForm.descData) {
        let exp = dataForm.conditionExpression;
        dataForm.descData.forEach((item) => {
          if (item && item.v && item.k) {
            dataForm.conditionDesc = dataForm.conditionDesc + item.v + "";
            exp = exp + item.v;
          }
        });
        dataForm.decisionExp = exp;
      }
    },
    // 新增表单 记录新增还是修改
    adddataFormSubmit() {
      // console.log(this.adddataForm);
      if (this.tempHeaderList.length <= 0) {
        this.$message.error("请添加表头信息");
        return;
      }

      if (!this.validForm()) {
        return;
      }

      let params = {};
      this.conditionList.forEach((item) => {
        for (var i = 0; i < this.adddataForm.length; i++) {
          let dataFrom = this.adddataForm[i];
          if (item.decisionCode === dataFrom.decisionCode) {
            this.setValueData(dataFrom, item);

            //记录是修改还是新增
            if (this.isIndex != undefined && this.isIndex >= 0) {
              if (dataFrom.decisionCode === "RCODE") {
                dataFrom.editType = constant.EDIT; //修改
              }
            } else {
              if (dataFrom.decisionCode === "RCODE") {
                dataFrom.editType = constant.ADD; //新增
              }
            }

            params[dataFrom.decisionCode] = dataFrom;
            break;
          }
        }
      });

      if (this.isIndex != undefined && this.isIndex >= 0) {
        // this.tableDatas[this.isIndex]=params
        this.$set(this.tableDatas, this.isIndex, params);
      } else {
        this.tableDatas.push(params);
      }

      this.addvisible = false;
      // console.log(this.tableDatas);
      // console.log(this.conditionList);
    },

    // 最终赋值
    setValueData(dataFrom, item) {
      // console.log(dataFrom, item);
      dataFrom.remark = JSON.stringify(dataFrom.descData);
      if (dataFrom.conditionType === "4") {
        //因子
        if (dataFrom.isExcute === "Y") {
          //非方法
          if (dataFrom.divisor.divisorType === "0") {
            //因子类型为输入值
            if (dataFrom.divisor.valueType === "2") {
              if (dataFrom.divisor.itemValueType != "3") {
                //非模型
                dataFrom.conditionDesc = dataFrom.rightValue;
                dataFrom.decisionExp =
                  dataFrom.conditionExpression + dataFrom.rightValue;
              } else {
                this.showValue(dataFrom);
              }
            } else {
              //固定值
              dataFrom.conditionDesc = dataFrom.isExcute;
              dataFrom.decisionExp = dataFrom.conditionExpression;
            }
          } else {
            //方法参数处理
            if (dataFrom.divisorMethodParams) {
              let inputValue = "";
              let newValue = "";
              if (dataFrom.headType == "1") {
                newValue = "ClmUtil." + dataFrom.divisor.divisorMethod;
              } else {
                newValue = "ActionUtil." + dataFrom.divisor.divisorMethod;
              }

              for (var j = 0; j < dataFrom.divisorMethodParams.length; j++) {
                let value = dataFrom.divisorMethodParams[j].name;
                let params = dataFrom.divisorMethodParams[j].attri; //参数名称

                inputValue += value + ",";
                let p = "$" + params + "$";
                if (dataFrom.divisorMethodParams[j].type === "String") {
                  newValue = newValue.replace(p, '"' + value + '"');
                } else {
                  newValue = newValue.replace(p, value);
                }
              }
              inputValue = inputValue.substring(0, inputValue.length - 1);
              dataFrom.conditionDesc = inputValue;
              dataFrom.decisionExp = newValue;
              dataFrom.methodParams = JSON.stringify(
                dataFrom.divisorMethodParams
              );
              // console.log(dataFrom.methodParams);
            } else {
              dataFrom.conditionDesc = dataFrom.isExcute;
              dataFrom.decisionExp = dataFrom.conditionExpression;
            }
          }
        } else if (dataFrom.isExcute === "N") {
          dataFrom.conditionDesc = dataFrom.isExcute;
          //非方法
          if (dataFrom.divisor.divisorType === "0") {
            //因子类型为输入值
            if (dataFrom.divisor.valueType === "2") {
              if (dataFrom.divisor.itemValueType != "3") {
                //非模型
                dataFrom.conditionDesc = dataFrom.rightValue;
                dataFrom.decisionExp =
                  dataFrom.conditionExpression + dataFrom.rightValue;
              } else {
                this.showValue(dataFrom);
              }
            } else {
              //固定值
              dataFrom.conditionDesc = dataFrom.isExcute;
              dataFrom.decisionExp = dataFrom.conditionExpression;
            }
          } else {
            //方法参数处理
            if (dataFrom.divisorMethodParams) {
              let inputValue = "";
              let newValue = "";
              if (dataFrom.headType == "1") {
                newValue = "ClmUtil." + dataFrom.divisor.divisorMethod;
              } else {
                newValue = "ActionUtil." + dataFrom.divisor.divisorMethod;
              }
              dataFrom.conditionDesc = inputValue;
              dataFrom.decisionExp = newValue;
              dataFrom.methodParams = JSON.stringify(
                dataFrom.divisorMethodParams
              );
              // console.log(dataFrom.methodParams);
            } else {
              dataFrom.conditionDesc = dataFrom.isExcute;
              dataFrom.decisionExp = dataFrom.conditionExpression;
            }
          }
        } else {
          dataFrom.conditionDesc = dataFrom.isExcute;
        }
      }
    },

    // 刷新表值
    getConditionData(data) {
      // console.log(data);
      let newData = [];
      this.tableDatas.forEach((item, index) => {
        if (index == this.rowIndex) {
          item[data.decisionCode] = JSON.parse(JSON.stringify(data));
        }
        newData.push(item);
      });
      this.tableDatas = newData;
      // console.log(this.tableDatas);
    },

    //复制 新增一行决策表值
    addDecisionRow(ele, index) {
      this.$emit("changeisCard", ele);
      // this.adddataForm = [];
      // let data = JSON.parse(JSON.stringify(this.tableDatas[index]));
      // this.conditionList.forEach((item) => {
      //   let dataForm = this.setInitData(data[item.decisionCode], item);
      //   dataForm.descData = new Array();
      //   dataForm.id = null;
      //   if (dataForm.decisionCode === "RCODE") {
      //     dataForm.conditionDesc = "";
      //     dataForm.decisionExp = "";
      //   }
      //   dataForm.descData = JSON.parse(dataForm.remark);
      //   dataForm["conditionDesc1"] = item.conditionDesc;
      //   // params[item.decisionCode] = dataForm
      //   this.adddataForm.push(dataForm);
      // });
      // this.addvisible = true;
      // console.log(this.adddataForm);
      // this.isIndex = null;
      // // console.log(this.tableDatas);
      // // this.tableDatas.push(params);
      // this.isadddataForm();
    },
    initHeader() {
      this.conditionList = [];
      // console.log(this.ruleList);
      this.ruleList.forEach((item) => {
        this.conditionList.push(item);
      });
      this.tempHeaderList.forEach((item) => {
        this.conditionList.push(item);
      });
    },
    //刷新决策表头列表
    getConditionDataList(data) {
      // console.log(data, this.conditionList);

      //记录新增头部
      this.recodes.addHead = true;
      if (this.chooseIndex != null) {
        this.conditionList[this.chooseIndex] = data;
      } else {
        if (this.tempHeaderList.length > 0) {
          let flag = false;
          this.tempHeaderList.forEach((item) => {
            if (
              item.conditionExpression === data.conditionExpression &&
              item.headType === data.headType
            ) {
              flag = true;
            }
          });
          if (flag) {
            this.$message.error("已存在相同表头信息，请重新添加");
            return;
          }
          let arr = [];
          this.tempHeaderList.forEach((e) => {
            arr.push(Number(e.decisionCode.replace("D000", "")));
          });
          // console.log(arr);
          let code = Math.max(...arr);
          data.decisionCode = "D000" + Number(code + 1);
        } else {
          data.decisionCode = "D000" + Number(this.tempHeaderList.length + 1);
        }

        if (data.headType === "1") {
          // this.conditionList.unshift(data);
          this.tempHeaderList.unshift(data);
        } else {
          // this.conditionList.push(data);
          this.tempHeaderList.push(data);
        }
      }
      this.initHeader();

      // console.log(this.tableDatas);
      // 已经新增的行 添加列
      if (this.tableDatas.length > 0) {
        this.tableDatas.forEach((item, index) => {
          item[data.decisionCode] = {
            id: null,
            isExcute: "Y", //默认不执行
            conditionType: "",
            divisorId: null,
            leftProperty: null,
            rightProperty: null,
            leftEntityId: null,
            rightEntityId: null,
            sysbol: "",
            rightValue: "",
            decisionExp: "",
            conditionExpression: "",
            conditionDesc: "",
            ["conditionDesc1"]: "",
            conditionMethodType: "",
            methodParams: "",
            isEffect: null,
            methodName: "",
            remark: "",
            descData: new Array(),
            showMthod: false,
            methodParas: [],
            showTxt: false,
            showSysbol: false,
            divisor: {
              configDate: null,
              configUser: null,
              creTime: null,
              creUserId: null,
              divisorIdentify: null,
              divisorMethod: null,
              divisorName: null,
              divisorType: null,
              entityId: null,
              id: null,
              isEffect: null,
              itemId: null,
              itemIdentify: null,
              itemTxtLength: null,
              itemTxtType: null,
              itemValueType: null,
              methodDesc: null,
              methodExpression: null,
              methodParams: null,
              methodType: null,
              remark: null,
              sysbol: null,
            },
          };
          item[data.decisionCode] = JSON.parse(JSON.stringify(data));
          item[data.decisionCode].conditionDesc = null;
          item[data.decisionCode].isExcute = "Y";
        });
      }

      // console.log(this.tableDatas, this.conditionList);
    },

    //1-添加决策表条件列 2-添加决策表动作列
    addConditionCol(type) {
      // if (this.checkEntity.length <= 0) {
      //     this.$message.error("请关联实体");
      //     return;
      // }
      this.chooseIndex = null;
      if (type == "1") {
        this.addConditionVisible = true;
        this.$nextTick(() => {
          this.$refs.addCondition.init();
        });
      } else if (type == "2") {
        this.addactionVisible = true;
        this.$nextTick(() => {
          this.$refs.addaction.init();
        });
      }
    },

    toList() {
      constant.clearTag(this);
      this.$router.push({
        path: "/drools-ruleConfig/group/add-or-update/" + this.dataForm.id,
      });
    },

    //初始化规则组信息
    init(id) {
      this.visible = true;
      // 规则组冲突
      if (!this.isconflict) {
        this.initDecision();
      } else {
      }
      this.initDivisor();
      this.initRuleInfo();
      this.isDisabled = false;
      this.entitysProperties = [];
      // this.$nextTick(()=>{
      //   this.getEntityProperties();
      // })
      // this.checkEntity = this.dataForm.checkEntity;
    },

    //初始化表头规则名称规则编码
    initRuleInfo() {},
    // 获取编辑规则数据
    getChangeClashInfo(dataForm, decisionList) {
      let params = {
        groupIdentify: dataForm.groupIdentify,
        taskNo: dataForm.taskNo,
        decisionList: decisionList,
      };
      changeClashInfo(params).then((res) => {
        if (res.data.data) {
          this.tableDatas = res.data.data.body;
          // console.log(this.tableDatas, "eDatas");
          this.conditionList = res.data.data.head;

          //除去规则名称和编码的表头
          if (this.conditionList && this.conditionList.length > 0) {
            this.tempHeaderList = [];
            this.conditionList.forEach((item) => {
              if (
                item.decisionCode != "RNAME" &&
                item.decisionCode != "RCODE"
              ) {
                this.tempHeaderList.push(item);
              }
            });
          } else {
            this.ruleList.forEach((item) => {
              this.conditionList.push(item);
            });
          }
          // console.log("初始化头部信息:" + JSON.stringify(this.conditionList));
        }
      });
    },
    //初始化规则组下已有决策表信息
    initDecision() {},

    // 获取实体类的属性
    getEntityProperties() {
      entityList({}).then((res) => {
        if (res.data.data) {
          this.entitysProperties = [];
          res.data.data.forEach((item) => {
            item["label"] = item.entityIdentify + " -- " + item.entityName;
            this.entitysProperties.push(item);
          });

          if (this.isconflict) {
            this.entityList = [];
            this.entitysProperties.forEach((e) => {
              let entity = {
                entityName: e.entityName,
                entityIdentify: e.entityIdentify,
                entityId: e.entityId,
                pkgName: e.pkgName,
              };
              this.entityList.push(entity);
              // console.log(this.entityList,'entityList');
            });
          } else {
            this.entityList = [];
            this.checkEntity.forEach((item) => {
              this.entitysProperties.forEach((e) => {
                if (item.entityId === e.entityId) {
                  let entity = {
                    entityName: e.entityName,
                    entityIdentify: e.entityIdentify,
                    entityId: e.entityId,
                    pkgName: e.pkgName,
                  };
                  this.entityList.push(entity);
                  // console.log(this.entityList,'entityList');
                }
              });
            });
          }
        }
      });
    },

    // 表单提交
    dataFormSubmit() {
      // console.log(this.checkEntity);

      let values = [];
      if (this.tableDatas.length > 0) {
        for (var i = 0; i < this.tableDatas.length; i++) {
          let data = this.tableDatas[i];
          if (data) {
            this.conditionList.forEach((item) => {
              // console.log(data, this.conditionList);
              if (data[item.decisionCode]) {
                data[item.decisionCode]["rowIndex"] = i;
                values.push(data[item.decisionCode]);
              }
            });
          }
        }
      }
      // console.log(values);

      let params = {
        groupIdentify: this.dataForm.groupIdentify,
        heads: JSON.stringify(this.conditionList),
        values: JSON.stringify(values),
        delList: JSON.stringify(this.delList),
        delHeadList: JSON.stringify(this.delHeadList),
      };
      this.$store.dispatch("loading/CHANGE_LOADING", true);
      saveDecisions(params)
        .then((res) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
          if (res.data && res.data.resultCode === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.visible = false;

                // this.$emit('refreshDataList')
                this.toList();
              },
            });
          } else {
            this.$message.error(res.data.resultMsg);
          }
        })
        .catch((err) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
        });
    },
  },
  filters: {},
};
</script>

<style lang="scss">
.el-table__row .el-form-item__content {
  margin-left: 0 !important;
}

.el-table__row .el-form-item {
  margin-bottom: 0 !important;
}

.yellow {
  background: yellow !important;
}

.red {
  background: red !important;
}
</style>
